//
//  EventTableView.m
//  Remind
//
//  Created by mac on 17/9/28.
//  Copyright © 2017年 2017.09.27. All rights reserved.
//

#import "EventTableView.h"
#import "EventTableViewCell.h"
#import "DataCach.h"
#import "Date.h"
#import "AppDelegate.h"

@interface EventTableView ()<UITableViewDelegate,UITableViewDataSource>
{
    
}
@property (strong, nonatomic) AppDelegate *appDelegate;
@property (strong, nonatomic) UITableView *tabelView;
@property (strong, nonatomic) NSUserDefaults *userDefaults;
@property (strong, nonatomic) UILabel *massageLabel;
@property (strong, nonatomic) NSString *today;
@property (strong, nonatomic) NSString *tomorrow;
@property (strong, nonatomic) NSMutableArray *dataArr;
@end

@implementation EventTableView


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}

- (instancetype)initWithFrame:(CGRect)frame ClassName:(NSString * __nonnull)classname{
    self = [super initWithFrame:frame];
    if(self){
        self.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1.0];
        self.tabelView = [[UITableView alloc] initWithFrame:CGRectMake(8, 0, frame.size.width - 16, frame.size.height) style:UITableViewStylePlain];
        self.tabelView.delegate = self;
        self.tabelView.dataSource = self;
        self.tabelView.showsVerticalScrollIndicator = NO;
        self.tabelView.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1.0];
        [self addSubview:self.tabelView];
        
        [self.tabelView registerNib:[UINib nibWithNibName:@"EventTableViewCell" bundle:nil] forCellReuseIdentifier:@"eventCell"];
        self.classNames = classname;
        [self loadData];
        
    }
    return self;
}

- (NSString *)dateStringIsConvertedToNumbersString:(NSDictionary *)dict{
    NSString *date = [[NSString alloc] initWithString:[dict objectForKey:@"date"]];
    date = [[date substringToIndex:10] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    return date;
}

- (void)sort:(NSMutableArray *)arr Option:(NSInteger)op{
    for(int i = 0; i < arr.count - 1; i++) {
        NSDictionary *dict;
        
        for(int j = i + 1; j < arr.count; j++){
            
            NSString *previous = [self dateStringIsConvertedToNumbersString:arr[i]];
            NSString *next = [self dateStringIsConvertedToNumbersString:arr[j]];
            
            if(op?[previous intValue] < [next intValue]:[previous intValue] > [next intValue]){
                dict = arr[i];
                arr[i] = arr[j];
                arr[j] = dict;
            }
            
        }
        
    }
    
}

- (void)sortDateArr{
    NSMutableArray *pastArr = [NSMutableArray new];
    NSMutableArray *todayArr = [NSMutableArray new];
    NSMutableArray *tomorrowArr = [NSMutableArray new];
    for(NSDictionary *dict in _dataArr){
        NSString *str = [self dateStringIsConvertedToNumbersString:dict];
        if([str intValue] > [_tomorrow intValue]){
            [tomorrowArr addObject:dict];
        }
        if([str intValue] < [_today intValue]){
            [pastArr addObject:dict];
        }
        if([str intValue] == [_today intValue]||[str intValue] == [_tomorrow intValue]){
            [todayArr addObject:dict];
        }
    }
    if(pastArr.count >= 2&&todayArr.count >= 2&&tomorrowArr.count >= 2){
        [self sort:pastArr Option:1];
        [self sort:todayArr Option:0];
        [self sort:tomorrowArr Option:0];
    }
    _dataArr = [NSMutableArray new];
    NSArray *arrs = [[NSArray alloc] initWithObjects:todayArr, tomorrowArr, pastArr, nil];
    NSLog(@"今天%@",todayArr);
    NSLog(@"明天%@",tomorrowArr);
    NSLog(@"过去%@",pastArr);
    for(NSMutableArray *mutArr in arrs){
        for(NSDictionary *dict in mutArr){
            [_dataArr addObject:dict];
        }
    }
    NSLog(@"----%@----",_dataArr);
}

#pragma mark - 数据加载、排序、推送
- (void)loadData{
    _today = [Date dateToStr:[NSDate date] Formatter:@"yyyyMMdd"];
    _tomorrow = [Date GetTomorrowDay:[NSDate date] Formatter:@"yyyyMMdd"];
    _appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    NSString *name = [[DataCach getUserInformation] objectForKey:@"name"];
    NSMutableDictionary *user_Dict = [[NSUserDefaults standardUserDefaults] objectForKey:name];
    NSMutableDictionary *data = [user_Dict objectForKey:_classNames];
    NSLog(@"----事件数据%@----",data);
    if(data.allKeys.count != 0){
        _dataArr = [NSMutableArray new];
        for(NSString *key in data.allKeys){
            NSDictionary *dict = [data objectForKey:key];
            NSString *dateString = [self dateStringIsConvertedToNumbersString:dict];
            [_dataArr addObject:dict];
            if([dateString intValue] == [_today intValue]){
                [_appDelegate sendNotificationMassage:dict];
            }
        }
        [self sortDateArr];
        
        [_massageLabel removeFromSuperview];
        return ;
    }
    if(!_massageLabel){
        _massageLabel = [[UILabel alloc] init];
        _massageLabel.frame = CGRectMake((self.frame.size.width - 150)/2, (self.frame.size.height - 50)/2, 150, 50);
        _massageLabel.text = @"没有任何事件";
        _massageLabel.font = [UIFont systemFontOfSize:15];
        _massageLabel.textColor = [UIColor blackColor];
        _massageLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_massageLabel];
    }
}

- (void)reloadDatas{
    [self loadData];
    [_tabelView reloadData];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    EventTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"eventCell"];
    
    NSMutableDictionary *dict = _dataArr[indexPath.section];
    NSString *eventDateString = [dict objectForKey:@"date"];
    
    cell.eventName.text = [dict objectForKey:@"event"];
    cell.eventTime.text = eventDateString;
    
    NSString *start = [Date dateToStr:[NSDate date] Formatter:@"yyyy-MM-dd HH:mm:ss"];
    NSInteger day = [Date betweenTheDays:start toDate:eventDateString];
    cell.intervalTime.textColor = [UIColor colorWithWhite:0.8 alpha:1.0];
    cell.intervalTime.attributedText = [self time:day Cell:cell];
    cell.backgroundColor = [UIColor clearColor];
    cell.MyBackGroundView.layer.cornerRadius = 10.0;
    return cell;
    
}

//根据距离今天的时间设置右下角Label的文字和颜色
- (NSAttributedString *)time:(NSInteger)day Cell:(EventTableViewCell *)cell{
    NSString *massage;
    if(day<0){
        massage = [[NSString alloc] initWithFormat:@"过了%ld天",labs(day)];
        cell.massage = [massage copy];
        cell.myImgView.image = [UIImage imageNamed:@"调皮"];
        return [self setAttributedString:massage AttributesColor:[UIColor orangeColor] FontSize:35  Rang:NSMakeRange(2,  massage.length - 2)];
    }
    if(day>1){
        massage = [[NSString alloc] initWithFormat:@"还有%ld天",day];
        cell.massage = [massage copy];
        cell.myImgView.image = [UIImage imageNamed:@"可爱"];
        return[self setAttributedString:massage AttributesColor:[UIColor colorWithRed:20/255.0 green:150/255.0 blue:200/255.0 alpha:1.0] FontSize:35 Rang:NSMakeRange(2, massage.length - 2)];
    }
    if(day == 1){
        massage = [[NSString alloc] initWithFormat:@"就剩%ld天",day];
        cell.massage = [massage copy];
        cell.myImgView.image = [UIImage imageNamed:@"生气"];
        return  [self setAttributedString:massage AttributesColor:[UIColor colorWithRed:248/255.0 green:219/255.0 blue:98/255.0 alpha:1.0] FontSize:35 Rang:NSMakeRange(2, 1)];
    }
    massage = @"就在今天";
    cell.massage = [massage copy];
    cell.myImgView.image = [UIImage imageNamed:@"生气"];
    return [self setAttributedString:massage AttributesColor:[UIColor redColor] FontSize:35 Rang:NSMakeRange(2, 1)];
}

- (NSAttributedString *)setAttributedString:(NSString *)str AttributesColor:(UIColor *)color FontSize:(CGFloat)size Rang:(NSRange)rang{
    NSMutableAttributedString *attMassage = [[NSMutableAttributedString alloc] initWithString:str];
    [attMassage addAttributes:@{NSForegroundColorAttributeName:color,NSFontAttributeName:[UIFont systemFontOfSize:size]} range:rang];
    [attMassage addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:30]} range:NSMakeRange(0, 2)];
    [attMassage addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithWhite:0.8 alpha:1.0],NSFontAttributeName:[UIFont systemFontOfSize:18]} range:NSMakeRange(str.length - 1, 1)];

    return [attMassage copy];

}

#pragma mark - 点击了cell之后代码块传参
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    EventTableViewCell *mycell = [tableView cellForRowAtIndexPath:indexPath];
    if(self.selectedBlock){
        NSDictionary *dict = [[NSDictionary alloc] initWithDictionary:_dataArr[indexPath.section]];
        NSMutableArray *arr = [NSMutableArray new];
        [arr addObject:[dict objectForKey:@"date"]];
        [arr addObject:[dict objectForKey:@"event"]];
        NSString *keyString = [arr componentsJoinedByString:@"-"];
        self.selectedBlock(keyString, _classNames, mycell.massage);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tabelView.frame.size.width, 30)];
    footerView.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1.0];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(20, 0, self.tabelView.frame.size.width - 40, 2)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.6 alpha:1.0];
    
    [footerView addSubview:lineView];
    return  footerView;
}


@end
